<template>
  <div class="app-container">
    <div style="padding:20px;">
      <el-form :inline="true" class="search-form">
        <el-row style="display: flex; flex-wrap: wrap">
          <div style="flex: 1">
            <el-form-item label="活动名称：">
              <el-input v-model="searchForm.keywords" placeholder="请输入名称" :maxlength="30" show-word-limit />
            </el-form-item>
            <el-form-item label="状态：">
              <el-select v-model="searchForm.status" placeholder="请选择状态">
                <el-option v-for="item in [
                    { name: '结束', id: '-1' },
                    { name: '已开始', id: '1' },
                    { name: '已关闭', id: '2' },
                    { name: '进行中', id: '3' },
                  ]" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
          <div style="text-align: right">
            <el-form-item>
              <el-button size="small" type="primary" icon="el-icon-search" @click="getListWay">查询</el-button>
              <el-button size="small" type="primary" icon="el-icon-refresh" @click="resetting">重置</el-button>
            </el-form-item>
          </div>
        </el-row>
      </el-form>
    </div>
    <el-divider></el-divider>
    <div class="" style="margin-top: 20px">
      <div class="marginBottom">
        <el-row :gutter="20">
          <el-col>
            <el-button icon="el-icon-circle-plus-outline" type="primary" size="small" @click="addWay">添加活动</el-button>
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="20">
        <el-col>
          <el-table v-loading="loading" :header-cell-style="{
              'background-color': '#f3f8fe',
              color: '#606266',
              height: '50px',
            }" highlight-current-row :data="dataList" style="width: 100%">
            <el-table-column align="center" prop="id" label="ID" />
            <el-table-column align="center" prop="activity_name" label="活动名称" />
            <el-table-column align="center" prop="start_time" label="开始时间" />
            <el-table-column align="center" prop="end_time" label="结束时间" />
            <!-- <el-table-column align="center" prop="status" label="商品">
              <template slot-scope="scope">
                <el-button type="text" @click="lookGoodsWay(scope.row)">查看活动商品</el-button>
              </template>
            </el-table-column> -->
            <el-table-column align="center" prop="status" label="状态">
              <template slot-scope="scope">
                <span v-if="scope.row.status == -1" style="color:#ff4949;">活动结束</span>
                <span v-if="scope.row.status == 1" style="color:#13ce66;">已开启</span>
                <span v-if="scope.row.status == 2" style="color:#81b337;">已关闭</span>
                <span v-if="scope.row.status == 3" style="color:#13ce66;">进行中</span>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" width="250" prop="address" label="操作">
              <template slot-scope="scope">
                <el-button style="margin: 5px" v-if="scope.row.status == 1 || scope.row.status == 3" type="warning"
                  size="mini" @click="saveStatus(scope.row)">
                  关闭活动
                </el-button>
                <el-button disabled style="margin: 5px" v-if="scope.row.status == -1" type="danger" size="mini">
                  活动结束
                </el-button>
                <el-button style="margin: 5px" v-if="scope.row.status == 2" type="success" size="mini"
                  @click="saveStatus(scope.row)">
                  开启活动
                </el-button>
                <el-button style="margin: 5px" type="primary" size="mini" @click="emitWay(scope.row)">
                  修改
                </el-button>
                <el-button style="margin: 5px" type="primary" size="mini" @click="emitWays(scope.row)">
                  详情
                </el-button>
                <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delWay(scope.row)">
                  <el-button slot="reference" style="margin: 5px"
                    :disabled="scope.row.status == 1 || scope.row.status == 3" type="danger" size="mini">
                    删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="marginTop" style="text-align: right">
        <el-pagination :current-page="searchForm.page" :page-sizes="[10, 20, 30, 40]" :page-size="searchForm.count"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </el-row>
    </div>

    <!-- 添加或者修改活动 -->
    <el-drawer :modal-append-to-body="false" :append-to-body="true" title="添加活动" size="78%" :withHeader="false"
      :visible.sync="dialogVisible" @close="handleClose" :show-close="true">
      <div style="position: relative;margin-bottom: 10px;">
        <div class="drawerTitle">
          <span>{{activityId ? '修改活动' : '添加活动'}}</span>
          <div class="close" @click="handleClose">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
      </div>
      <!-- <el-dialog
      :close-on-click-modal="false"
      :title="activityId ? '修改活动' : '添加活动'"
      :visible.sync="dialogVisible"
      width="1100px"
      @close="handleClose"
    > -->
    <el-scrollbar wrap-style="overflow-x:hidden;" style="height: calc(100vh - 150px)">
      <el-form v-loading="submitLoading" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px"
        class="demo-ruleForm">
        <div class="informationTitleView">
          <div class="leftBox">
            <div class="leftborder" />
            <div class="text">基本信息</div>
          </div>
          <div class="right" />
        </div>
        <el-row :span="24">
          <el-col :span="11">
            <el-form-item label="活动名称" prop="activity_name">
              <el-input v-model="ruleForm.activity_name" placeholder="请输入活动名称" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="20">

          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleForm.status" size="mini">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="2">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="时间段" prop="startEndTime">
              <el-date-picker v-model="ruleForm.startEndTime" style="width: 300px" type="datetimerange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="省市区" prop="cascaderRegList">
              <el-cascader v-model="cascaderRegList" style="width: 300px" :options="regionList" collapse-tags :props="{
                  multiple: true,
                  value: 'id',
                  label: 'name',
                  children: 'children',
                  checkStrictly: true,
                }" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="22" :offset="0">
            <el-form-item label="主图" prop="imageUrl">
              <logo-upload :single-file="ruleForm.imageUrl" :show-file-list="false" accept="image/jpeg, image/png"
                @uploadCallback="imageSuccBack" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="22">
            <el-form-item label="活动轮播">
              <logo-upload :file-list="ruleForm.carousel" :show-file-list="true" accept="image/jpeg, image/png"
                @uploadCallback="carouselBack" />
            </el-form-item>
          </el-col> -->
          <el-col :span="22">
            <el-form-item label="活动说明" prop="describe">
              <el-input v-model="ruleForm.describe" placeholder="请输入活动说明" type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="22" class="splitTitle">
            <div class="informationTitleView">
              <div class="leftBox">
                <div class="leftborder" />
                <div class="text">扩展信息</div>
              </div>
              <div class="right" />
            </div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="用户相关">
              <el-button type="primary" size="small" @click="showDrawer('user')">指定用户</el-button>
              <el-button type="primary" size="small" @click="showDrawer('user-group')">指定用户分组</el-button>
              <el-button type="primary" size="small" @click="showDrawer('user-label')">指定用户标签</el-button>
              <div v-if="choosedUserList.length > 0" style="margin-bottom: 10px">
                <span style="font-weight: bold">已选用户：</span>
                <el-tag v-for="user in choosedUserList" :key="user.id" style="margin-right: 10px" type="success"
                  size="mini" effect="dark">{{ user.nickname }}</el-tag>
              </div>
              <div v-if="choosedUserGroupList.length > 0" style="margin-bottom: 10px">
                <span style="font-weight: bold">已选用户分组：</span>
                <el-tag v-for="group in choosedUserGroupList" :key="group.id" style="margin-right: 10px" type="primary"
                  size="mini" effect="dark">{{ group.name }}</el-tag>
              </div>
              <div v-if="choosedUserLabelList.length > 0" style="margin-bottom: 10px">
                <span style="font-weight: bold">已选用户标签：</span>
                <el-tag v-for="label in choosedUserLabelList" :key="label.id" style="margin-right: 10px" type="warning"
                  size="mini" effect="dark">{{ label.tag_name }}</el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="参与活动商品" prop="chooseSkuList">
              <el-select v-model="tempChoosedGoods" style="width: 400px" :multiple="false" filterable remote
                reserve-keyword placeholder="关键字查询支持商品名、ID、副标题、编码" :remote-method="getGoodsListWay"
                :loading="isLoadingGoods" :disabled="ruleForm.startEndTime.length == 0" value-key="id"
                @change="handleChooseGoodsChange">
                <el-option v-for="item in GoodsList" :key="item.id" :label="item.name" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="skuList.length > 0 || confirmGoodsSkuList.length > 0">
              <el-tabs v-model="activeChooseGoodsName" @tab-click="handleChoooseGoodsClick">
                <el-tab-pane v-if="skuList.length > 0" label="填写返回比例" name="goChooseGoods">
                  <div>
                    <choosed-all-return-comp ref="chooseSeckillSkuRef" :display="false" :list="skuList"
                      @updatelist="handleCurrentChooseGoods" @deleteitem="handleDeleteItem" />
                  </div>
                </el-tab-pane>
                <el-tab-pane v-if="confirmGoodsSkuList.length > 0"
                  :label="'已确定返回比例(' + confirmGoodsSkuList.length + ')'" name="choosedList">
                  <choosed-all-return-comp ref="displayChooseSeckillSkuRef" :is-update="activityId ? true : false"
                    display :list="confirmGoodsSkuList" @updatelist="handleUpdateList" @deleteitem="handleDeleteItem" />
                </el-tab-pane>
              </el-tabs>
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item label="新用户条件" prop="new_user_factor">
              <el-radio-group v-model="ruleForm.new_user_factor" size="mini">
                <el-radio label="1">注册时间</el-radio>
                <el-radio label="2">未消费的商品</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="ruleForm.new_user_factor == 1" label="选择时间" prop="factor">
              <el-date-picker v-model="ruleForm.factor" type="datetime" placeholder="选择日期时间" />
            </el-form-item>
            <el-form-item v-else-if="ruleForm.new_user_factor == 2" label="选择平台商品" prop="goods_ids">
              <el-select v-model="ruleForm.goods_ids" multiple style="width: 100%" filterable remote reserve-keyword
                placeholder="关键字查询支持商品名、ID、副标题、编码" :remote-method="getPlatformGoodsList" :loading="goodsLoading">
                <el-option v-for="item in platFormGoodsList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="返现类型" prop="restriction_type">
              <el-radio-group v-model="ruleForm.restriction_type" size="mini">
                <el-radio label="1">按消费订单数限制</el-radio>
                <el-radio label="2">按消费金额限制</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="返现值" prop="restriction_value">
              <el-input-number v-model="ruleForm.restriction_value" size="mini" label="返现值" :controls="true"
                controls-position="both" :min="0" />(元)
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" :offset="0">
            <el-form-item label="第一天返回比例" prop="first_day_rate">
              <el-input-number v-model="ruleForm.first_day_rate" size="mini" label="第一天返回比例" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="第二天返回比例" prop="second_day_rate">
              <el-input-number v-model="ruleForm.second_day_rate" size="mini" label="第二天返回比例" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="第三天返回比例" prop="third_day_rate">
              <el-input-number v-model="ruleForm.third_day_rate" size="mini" label="第三天返回比例" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="最小返还值(分)" prop="min_rate">
              <el-input-number v-model="ruleForm.min_rate" size="mini" label="最小返还值(分)" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      </el-scrollbar>
      <div>
        <el-row style="margin: 20px 0">
          <el-col :span="24" style="text-align: right; padding-right: 30px;">
            <el-button @click="handleClose">取消</el-button>
            <el-button :loading="submitLoading" type="primary" @click="submitForm('ruleForm')">保存</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{
          activityId ? "修改" : "确定"
        }}</el-button>
      </span> -->
    </el-drawer>

    <!-- 添加或者修改活动 -->
    <!-- <el-dialog :close-on-click-modal="false" title="详情" :visible.sync="dialogVisibles" width="80%" @close="handleClose">
     -->
     <el-drawer :modal-append-to-body="false" :append-to-body="true" title="详情" size="78%" :withHeader="false"
       :visible.sync="dialogVisibles" @close="handleClose" :show-close="true">
      <div style="position: relative;margin-bottom: 10px;">
        <div class="drawerTitle">
          <span>活动详情</span>
          <div class="close" @click="handleClose">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
      </div>
      <el-form v-loading="submitLoading" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px"
        class="demo-ruleForm">
        <el-row :gutter="20">
          <el-col :span="24" class="splitTitle">
            <div class="informationTitleView">
              <div class="leftBox">
                <div class="leftborder" />
                <div class="text">基本信息</div>
              </div>
              <div class="right" />
            </div>
          </el-col>
          <el-col :span="11">
            <el-form-item label="活动名称" prop="activity_name">
              <el-input disabled v-model="ruleForm.activity_name" placeholder="请输入活动名称" maxlength="20"
                show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-radio-group disabled v-model="ruleForm.status" size="mini">
                <el-radio :label="1">开启</el-radio>
                <el-radio :label="2">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="时间段" prop="startEndTime">
              <el-date-picker disabled v-model="ruleForm.startEndTime" style="width: 100%" type="datetimerange"
                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="省市区" prop="cascaderRegList">
              <el-cascader disabled v-model="cascaderRegList" style="width: 100%" :options="regionList" collapse-tags
                :props="{
                  multiple: true,
                  value: 'id',
                  label: 'name',
                  children: 'children',
                  checkStrictly: true,
                }" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="22" :offset="0">
            <el-form-item label="主图" prop="imageUrl">
              <logo-upload :single-file="ruleForm.imageUrl" :show-file-list="false" accept="image/jpeg, image/png"
                @uploadCallback="imageSuccBack" />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="22">
            <el-form-item label="活动轮播">
              <logo-upload :file-list="ruleForm.carousel" :show-file-list="true" accept="image/jpeg, image/png"
                @uploadCallback="carouselBack" />
            </el-form-item>
          </el-col> -->
          <el-col :span="22">
            <el-form-item label="活动说明" prop="describe">
              <el-input disabled v-model="ruleForm.describe" placeholder="请输入活动说明" type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }" :maxlength="200" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24" class="splitTitle">
            <div class="informationTitleView">
              <div class="leftBox">
                <div class="leftborder" />
                <div class="text">扩展信息</div>
              </div>
              <div class="right" />
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户相关">
              <el-button disabled type="primary" size="small" @click="showDrawer('user')">指定用户</el-button>
              <el-button disabled type="primary" size="small" @click="showDrawer('user-group')">指定用户分组</el-button>
              <el-button type="primary" disabled size="small" @click="showDrawer('user-label')">指定用户标签</el-button>
              <div v-if="choosedUserList.length > 0" style="margin-bottom: 10px">
                <span style="font-weight: bold">已选用户：</span>
                <el-tag v-for="user in choosedUserList" :key="user.id" style="margin-right: 10px" type="success"
                  size="mini" effect="dark">{{ user.nickname }}</el-tag>
              </div>
              <div v-if="choosedUserGroupList.length > 0" style="margin-bottom: 10px">
                <span style="font-weight: bold">已选用户分组：</span>
                <el-tag v-for="group in choosedUserGroupList" :key="group.id" style="margin-right: 10px" type="primary"
                  size="mini" effect="dark">{{ group.name }}</el-tag>
              </div>
              <div v-if="choosedUserLabelList.length > 0" style="margin-bottom: 10px">
                <span style="font-weight: bold">已选用户标签：</span>
                <el-tag v-for="label in choosedUserLabelList" :key="label.id" style="margin-right: 10px" type="warning"
                  size="mini" effect="dark">{{ label.tag_name }}</el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="参与活动商品" prop="chooseSkuList">
              <el-select v-model="tempChoosedGoods" style="width: 400px" :multiple="false" filterable remote
                reserve-keyword placeholder="关键字查询支持商品名、ID、副标题、编码" :remote-method="getGoodsListWay"
                :loading="isLoadingGoods" disabled value-key="id" @change="handleChooseGoodsChange">
                <el-option v-for="item in GoodsList" :key="item.id" :label="item.name" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="skuList.length > 0 || confirmGoodsSkuList.length > 0">
              <el-tabs v-model="activeChooseGoodsName" @tab-click="handleChoooseGoodsClick">
                <el-tab-pane v-if="skuList.length > 0" label="填写返回比例" name="goChooseGoods">
                  <div>
                    <choosed-all-return-comp ref="chooseSeckillSkuRef" :display="false" :list="skuList"
                      @updatelist="handleCurrentChooseGoods" @deleteitem="handleDeleteItem" />
                  </div>
                </el-tab-pane>
                <el-tab-pane v-if="confirmGoodsSkuList.length > 0"
                  :label="'已确定返回比例(' + confirmGoodsSkuList.length + ')'" name="choosedList">
                  <choosed-all-return-comp ref="displayChooseSeckillSkuRef" :is-update="activityId ? true : false"
                    display :list="confirmGoodsSkuList" @updatelist="handleUpdateList" @deleteitem="handleDeleteItem" />
                </el-tab-pane>
              </el-tabs>
            </el-form-item>
          </el-col>

          <el-col :span="22">
            <el-form-item label="新用户条件" prop="new_user_factor">
              <el-radio-group disabled v-model="ruleForm.new_user_factor" size="mini">
                <el-radio label="1">注册时间</el-radio>
                <el-radio label="2">未消费的商品</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="ruleForm.new_user_factor == 1" label="选择时间" prop="factor">
              <el-date-picker disabled v-model="ruleForm.factor" type="datetime" placeholder="选择日期时间" />
            </el-form-item>
            <el-form-item v-else-if="ruleForm.new_user_factor == 2" label="选择平台商品" prop="goods_ids">
              <el-select disabled v-model="ruleForm.goods_ids" multiple style="width: 100%" filterable remote
                reserve-keyword placeholder="关键字查询支持商品名、ID、副标题、编码" :remote-method="getPlatformGoodsList"
                :loading="goodsLoading">
                <el-option v-for="item in platFormGoodsList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6" :offset="0">
            <el-form-item label="第一天返回比例" prop="first_day_rate">
              <el-input-number disabled v-model="ruleForm.first_day_rate" size="mini" label="第一天返回比例" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="第二天返回比例" prop="second_day_rate">
              <el-input-number disabled v-model="ruleForm.second_day_rate" size="mini" label="第二天返回比例" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="第三天返回比例" prop="third_day_rate">
              <el-input-number disabled v-model="ruleForm.third_day_rate" size="mini" label="第三天返回比例" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <el-form-item label="最小返还值(分)" prop="min_rate">
              <el-input-number disabled v-model="ruleForm.min_rate" size="mini" label="最小返还值(分)" :controls="true"
                controls-position="both" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span> -->
    </el-drawer>

    <!-- 查看商品 -->
    <el-dialog :close-on-click-modal="false" title="查看商品" :visible.sync="goodsLookDialog" width="800px">
      <el-row :gutter="20">
        <el-table v-loading="goodsLookLoading" :header-cell-style="{
            'background-color': '#f3f8fe',
            color: '#606266',
            height: '50px',
          }" highlight-current-row :data="GoodsDataList" style="width: 100%">
          <el-table-column align="center" prop="id" label="id" />
          <el-table-column align="center" prop="name" label="商品名称" />
          <el-table-column align="center" prop="main_image" label="主图">
            <template slot-scope="scope">
              <el-image v-if="scope.row.main_image" style="width: 50px" :src="scope.row.main_image" />
            </template>
          </el-table-column>
          <el-table-column align="center" prop="subtitle" label="副标题" />
        </el-table>
      </el-row>
    </el-dialog>

    <!-- 指定用户信息 -->
    <el-drawer :modal-append-to-body="false" :append-to-body="true" title="指定用户信息" size="60%" :withHeader="false"
      :visible.sync="isShowDrawer" @close="handleCloseDrawer" :show-close="true">
    <!-- <el-drawer title="指定用户信息" :visible.sync="isShowDrawer" direction="rtl" size="1200px" @close="handleCloseDrawer">
      -->
      <div style="position: relative">
        <div class="drawerTitle">
          <span>指定用户信息</span>
          <div class="close" @click="handleCloseDrawer">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
      </div>
      <div style="padding: 20px 30px 0">
        <div v-if="choosedUserList.length > 0" style="margin-bottom: 10px">
          <span style="font-weight: bold">已选用户：</span>
          <el-tag v-for="user in choosedUserList" :key="user.id" style="margin-right: 10px" type="success" size="mini"
            effect="dark">{{ user.nickname }}</el-tag>
        </div>
        <div v-if="choosedUserGroupList.length > 0" style="margin-bottom: 10px">
          <span style="font-weight: bold">已选用户分组：</span>
          <el-tag v-for="group in choosedUserGroupList" :key="group.id" style="margin-right: 10px" type="primary"
            size="mini" effect="dark">{{ group.name }}</el-tag>
        </div>
        <div v-if="choosedUserLabelList.length > 0" style="margin-bottom: 10px">
          <span style="font-weight: bold">已选用户标签：</span>
          <el-tag v-for="label in choosedUserLabelList" :key="label.id" style="margin-right: 10px" type="warning"
            size="mini" effect="dark">{{ label.tag_name }}</el-tag>
        </div>

        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="指定用户" name="user">
            <user-list-comp ref="userListRef" @userchoosechange="handleChoosedUserChange" />
          </el-tab-pane>
          <el-tab-pane label="指定用户分组" name="user-group">
            <user-group-comp ref="userGroupRef" @usergruopchange="handleUserGroupChange" />
          </el-tab-pane>
          <el-tab-pane label="指定用户标签" name="user-label">
            <user-label-comp ref="userLabelRef" @userlabelchange="handleUserLabelChange" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {
    getRestitutionList,
    getLoveFarmerGoodsList,
    delRestitution,
    editStatusRestitution,
    detailRestitution,
    addRestitution,
    editRestitution,
  } from "@/api/activity/agriculture";
  // 获取平台商品列表
  import {
    getGoodsList
  } from "@/api/commodity/index";
  import {
    getRegionList
  } from "@/api/user/index";
  import {
    getActivityGoodsList
  } from "@/api/index";
  import LogoUpload from "@/components/FileUpload";
  import {
    parseTime
  } from "@/utils/index";
  import UserListComp from "../seckill/components/UserList.vue";
  import UserGroupComp from "../seckill/components/UserGroup.vue";
  import UserLabelComp from "../seckill/components/UserLabel.vue";
  import ChoosedAllReturnComp from "./components/ChoosedAllReturnComp.vue";
  export default {
    name: "AllReturn",
    components: {
      LogoUpload,
      UserListComp,
      UserGroupComp,
      UserLabelComp,
      ChoosedAllReturnComp,
    },
    data() {
      // const mainImageValidator = (rule, value, callback) => {
      //   if (!this.ruleForm.imageUrl.url) {
      //     callback(new Error("请上传商品主图"));
      //   } else {
      //     callback();
      //   }
      // };
      const choosedSeckillSkuListValidator = (rule, value, callback) => {
        if (this.ruleForm.chooseSkuList.length === 0) {
          callback(new Error("至少选择一个商品"));
        } else {
          callback();
        }
      };
      const validatorRate = (rule, value, callback) => {
        if (value > 100) {
          console.log("执行了吗？。。。。");
          callback(new Error("最大值为100!"));
        } else if (value < 0) {
          callback(new Error("最小值为零"));
        } else {
          callback();
        }
      };
      return {
        loading: false,
        searchForm: {
          keywords: "",
          count: 10,
          page: 1,
          status: "",
        },
        dataList: [],
        total: 0,
        // 省市区列表
        regionList: [],
        title: "添加活动",
        dialogVisible: false,
        ruleForm: {
          id: "",
          activity_name: "",
          status: 2,
          describe: "",
          imageUrl: {},
          area_ids_json: "",
          start_time: "",
          end_time: "",
          carousel: [],
          startEndTime: [],
          goods_ids: [], // 选择平台商品
          chooseSkuList: [], // 选中的三天全返商品规格列表
          new_user_factor: "",
          factor: "",
          first_day_rate: "",
          second_day_rate: "",
          third_day_rate: "",
          min_rate: "", // 最小返还值(分)
          restriction_type: "1",
          restriction_value: "",
        },
        submitLoading: false,

        // 省市区回显
        cascaderRegList: [],
        rules: {
          activity_name: [{
            required: true,
            validator: (rule, value, callback) => {
              const req = /[^a-zA-Z0-9\u4e00-\u9fa5]/g;
              if (!value) {
                return callback(new Error("请输入活动名称"));
              } else {
                if (req.test(value)) {
                  return callback(new Error("活动名称不能存在特殊字符"));
                }
                callback();
              }
            },
            trigger: "change",
          }, ],

          describe: [{
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("请输入活动说明"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          }, ],
          // imageUrl: [{
          //   required: true,
          //   validator: mainImageValidator,
          //   trigger: "blur",
          // }, ],
          // carousel: [{
          //   required: true,
          //   validator: (rule, value, callback) => {
          //     if (this.ruleForm.carousel.length === 0) {
          //       return callback(new Error("请上传轮播图片"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: "blur",
          // }, ],
          startEndTime: [{
            required: true,
            message: "开始结束时间必填",
            trigger: "blur"
          }, ],
          chooseSkuList: [{
            required: true,
            validator: choosedSeckillSkuListValidator,
            trigger: "blur",
          }, ],
          new_user_factor: [{
            required: true,
            message: "请选择新用户条件",
            trigger: "blur"
          }, ],
          factor: [{
            required: true,
            message: "请选择条件时间或者商品",
            trigger: "blur",
          }, ],
          goods_ids: [{
            required: true,
            message: "请选择平台商品",
            trigger: "blur"
          }, ],
          first_day_rate: [{
              required: true,
              message: "请填写第一天返回比例",
              trigger: "blur"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "change"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "blur"
            },
          ],
          second_day_rate: [{
              required: true,
              message: "请填写第二天返回比例",
              trigger: "blur"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "change"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "blur"
            },
          ],
          third_day_rate: [{
              required: true,
              message: "请填写第三天返回比例",
              trigger: "blur"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "change"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "blur"
            },
          ],
          min_rate: [{
              required: true,
              message: "请填写最小返还值",
              trigger: "blur"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "change"
            },
            {
              required: true,
              validator: validatorRate,
              trigger: "blur"
            },
          ],
        },
        goodsSaerch: {
          keywords: "",
          page: 1,
          count: 20,
        },

        goodsLoading: false,
        goodsLookLoading: false,
        goodsLookDialog: false,
        GoodsDataList: [],

        isShowDrawer: false,
        activeName: "user", // user , user-group,user-label
        choosedUserList: [], // 选中的用户
        choosedUserGroupList: [], // 选中的用户分组
        choosedUserLabelList: [], // 选中的用户标签
        confirmGoodsSkuList: [], // 确定的全返商品列表
        activeChooseGoodsName: "goChooseGoods", // goChooseGoods  choosedList
        isLoadingGoods: false,
        GoodsList: [], // 搜索出来的商品列表
        tempChoosedGoods: {},
        skuList: [],
        activityId: "", // 活动ID 编辑时使用
        platFormGoodsList: [], // 平台商品列表
        dialogVisibles: false,
      };
    },
    watch: {},
    created() {
      getRegionList().then((res) => {
        this.regionList = res.data;
      });
      this.getListWay();
    },
    methods: {
      getListWay() {
        this.loading = true;
        getRestitutionList(this.searchForm)
          .then((res) => {
            this.loading = false;
            this.dataList = res.data.list;
            this.total = res.data.total;
          })
          .catch((err) => {
            this.loading = false;
            this.$messages.error(err.msg);
          });
      },
      resetting() {
        this.searchForm = {
          activity_name: "",
          count: 10,
          page: 1,
          status: "",
        };
        this.getListWay();
      },
      addWay() {
        this.handleClose();
        this.title = "添加活动";
        this.dialogVisible = true;
      },
      delWay(row) {
        this.loading = true;
        delRestitution({
            id: row.id
          })
          .then(() => {
            this.$messages.success("删除成功");
            this.getListWay();
          })
          .catch((err) => {
            this.loading = false;
            this.$messages.error(err.msg);
          });
      },
      async getActivityDetail() {
        this.submitLoading = true;
        const res = await detailRestitution({
          id: this.activityId
        });
        const {
          code,
          data,
          msg
        } = res;
        if (code === 200) {
          this.ruleForm.activity_name = data.activity_name;
          this.ruleForm.describe = data.describe;
          this.ruleForm.address = JSON.parse(data.cover_region_json);
          this.ruleForm.startEndTime = [
            new Date(data.start_time),
            new Date(data.end_time),
          ];

          this.ruleForm.imageUrl = {
            url: JSON.parse(data.image)
          };
          // this.ruleForm.image = JSON.parse(data.image);
          this.ruleForm.new_user_factor = String(data.new_user_factor);
          this.ruleForm.first_day_rate = data.first_day_rate;
          this.ruleForm.second_day_rate = data.second_day_rate;
          this.ruleForm.third_day_rate = data.third_day_rate;
          this.ruleForm.min_rate = data.min_rate;
          this.ruleForm.restriction_type = String(data.restriction_type);
          this.ruleForm.restriction_value = data.restriction_value;
          // this.ruleForm.status = data.status;
          // this.ruleForm.imageUrl = data.imageUrl;
          this.ruleForm.carousel = JSON.parse(data.images).map((item) => ({
            url: item.url,
          }));

          // this.ruleForm.status = data.status;
          // 回显数据
          this.redisplayData(data);
        } else {
          this.$message.error(msg);
        }
        this.submitLoading = false;
      },
      // 回显数据
      redisplayData(data) {
        if (data.cover_user) {
          const coverUserIdArr = data.cover_user.split(",");
          const coverUserNameArr = data.cover_user_name.split(",");
          coverUserIdArr.forEach((item, index) => {
            this.choosedUserList.push({
              id: item,
              nickname: coverUserNameArr[index],
            });
          });
        }

        if (data.cover_group) {
          const coverGroupIdArr = data.cover_group.split(",");
          const coverGroupNameArr = data.cover_group_name.split(",");
          coverGroupIdArr.forEach((item, index) => {
            this.choosedUserGroupList.push({
              id: item,
              name: coverGroupNameArr[index],
            });
          });
        }
        if (data.cover_label) {
          const coverLabelIdArr = data.cover_label.split(",");
          const coverLabelNameArr = data.cover_label_name.split(",");

          coverLabelIdArr.forEach((item, index) => {
            this.choosedUserLabelList.push({
              id: item,
              tag_name: coverLabelNameArr[index],
            });
          });
        }
        if (data.cover_region_json) {
          this.cascaderRegList = JSON.parse(data.cover_region_json);
        }
        if (Number(data.new_user_factor) === 1) {
          this.ruleForm.factor = new Date(Number(data.factor) * 1000);
        } else if (Number(data.new_user_factor) === 2) {
          this.ruleForm.goods_ids = data.factor.split(",");
        }
        data.restitution.forEach((item) => {
          this.$set(item, "isConfirm", false);
          this.$set(item, "isUpdate", false);
        });
        this.confirmGoodsSkuList = data.restitution;
      },
      emitWay(row) {
        this.dialogVisible = true;
        this.activityId = row.id;
        this.activeChooseGoodsName = "choosedList";
        this.getActivityDetail();
      },
      emitWays(row) {
        this.dialogVisibles = true;
        this.activityId = row.id;
        this.activeChooseGoodsName = "choosedList";
        this.getActivityDetail();
      },
      saveStatus(row) {
        var obj = {
          id: row.id,
          action: "restitution",
        };
        this.loading = true;
        editStatusRestitution(obj)
          .then((res) => {
            this.$messages.success("操作成功");
            this.getListWay();
          })
          .catch((err) => {
            this.$messages.error(err.msg);
            this.loading = false;
          });
      },
      valueFormaChange(val) {},
      submitForm(formName) {
        this.ruleForm.chooseSkuList = [];
        this.confirmGoodsSkuList.forEach((item) => {
          const newItem = {
            goods_id: item.goods_id,
            first_day_rate: item.first_day_rate,
            second_day_rate: item.second_day_rate,
            third_day_rate: item.third_day_rate,
          };
          if (item.product_id) {
            newItem.id = item.id;
            newItem.product_id = item.product_id;
          } else {
            newItem.product_id = item.id;
          }
          this.ruleForm.chooseSkuList.push(newItem);
        });
        this.ruleForm.images = this.ruleForm.carousel.map((item) => ({
          url: item.url,
          link_url: "",
        }));
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const totalRate =
              Number(this.ruleForm.first_day_rate) +
              Number(this.ruleForm.second_day_rate) +
              Number(this.ruleForm.third_day_rate);
            if (totalRate !== 100) {
              this.$message.warning("三天返回比例综合不等于百分之百");
              return;
            }
            // 开始规整数据
            this.submitLoading = true;
            if (this.cascaderRegList.length !== 0) {
              this.ruleForm.area_ids_json = JSON.stringify(this.cascaderRegList);
            }
            if (String(this.ruleForm.new_user_factor) === "1") {
              this.ruleForm.factor =
                new Date(this.ruleForm.factor).getTime() / 1000;
            } else if (String(this.ruleForm.new_user_factor) === "2") {
              this.ruleForm.factor = this.ruleForm.goods_ids.join(",");
            }
            console.log(this.ruleForm.image);
            const paramsObj = {
              activity_name: this.ruleForm.activity_name,
              describe: this.ruleForm.describe,
              start_time: parseTime(this.ruleForm.startEndTime[0]),
              end_time: parseTime(this.ruleForm.startEndTime[1]),
              status: this.ruleForm.status,
              image: JSON.stringify(this.ruleForm.imageUrl.url),
              images: JSON.stringify(
                this.ruleForm.carousel.map((item) => ({
                  url: item.url,
                  link_url: "",
                }))
              ),
              cover_region_json: this.ruleForm.area_ids_json,
              cover_user: this.choosedUserList.map((item) => item.id).join(","),
              cover_label: this.choosedUserLabelList
                .map((item) => item.id)
                .join(","),
              cover_group: this.choosedUserGroupList
                .map((item) => item.id)
                .join(","),
              new_user_factor: this.ruleForm.new_user_factor,
              factor: this.ruleForm.factor,
              first_day_rate: this.ruleForm.first_day_rate,
              second_day_rate: this.ruleForm.second_day_rate,
              third_day_rate: this.ruleForm.third_day_rate,
              min_rate: this.ruleForm.min_rate,
              restitution: this.ruleForm.chooseSkuList,
              restriction_type: this.ruleForm.restriction_type,
              restriction_value: this.ruleForm.restriction_value,
            };
            // return;
            let api = null;
            if (this.activityId) {
              api = editRestitution;
              paramsObj.id = this.activityId;
            } else {
              api = addRestitution;
            }
            api(paramsObj)
              .then((res) => {
                const {
                  code,
                  msg,
                  status
                } = res;
                this.submitLoading = false;
                this.dialogVisible = false;
                this.getListWay();
                this.resetRuleForm();
                if (code === 200 && status === 1) {
                  this.$message.success(msg);
                } else {
                  this.$message.error(msg);
                }
              })
              .catch((err) => {
                this.resetRuleForm();
                this.$message.error(err);
                this.submitLoading = false;
                this.dialogVisible = false;
              });
          } else {
            this.$message.error("请检查：有部分信息或图片尚未添加完整!");
            return false;
          }
        });
      },
      handleClose() {
        this.dialogVisible = false;
        this.dialogVisibles = false;

        this.cascaderRegList = [];
        this.images = [];

        this.resetRuleForm();
      },
      resetRuleForm() {
        this.ruleForm = this.$options.data().ruleForm;
        this.choosedUserList = [];
        this.choosedUserLabelList = [];
        this.choosedUserGroupList = [];
        this.ruleForm.chooseSkuList = [];
        this.confirmGoodsSkuList = [];
        this.activityId = "";
        this.skuList = [];
      },
      getGoodsListWay(query) {
        if (query !== "") {
          this.isLoadingGoods = true;
          this.goodsSaerch.keywords = query;
          var obj = {
            ...this.goodsSaerch,
            action: "restitution",
            start_time: parseTime(this.ruleForm.startEndTime[0]),
            end_time: parseTime(this.ruleForm.startEndTime[1]),
          };
          getActivityGoodsList(obj)
            .then((res) => {
              this.isLoadingGoods = false;
              this.GoodsList = res.data.list;
              this.goodsTotal = res.data.total;
            })
            .catch((err) => {
              this.$messages.error(err.msg);
              this.isLoadingGoods = false;
            });
        } else {
          this.GoodsList = [];
        }
      },
      // 查看商品列表
      lookGoodsWay(row) {
        this.goodsLookDialog = true;
        this.goodsLookLoading = true;
        getLoveFarmerGoodsList({
            activity_id: row.id
          })
          .then((res) => {
            this.GoodsDataList = res.data;
            this.goodsLookLoading = false;
          })
          .catch((err) => {
            this.goodsLookLoading = false;
            this.goodsLookDialog = false;
            this.$messages.error(err.msg);
          });
      },
      handleSizeChange(val) {
        this.searchForm.count = val;
        this.getListWay();
      },
      handleCurrentChange(val) {
        this.searchForm.page = val;
        this.getListWay();
      },
      carouselBack(res) {
        this.ruleForm.carousel = res;
      },
      // 主图上传成功
      imageSuccBack(res) {
        this.ruleForm.imageUrl = res;
        this.ruleForm.image = {
          url: res.url,
          link_url: "",
        };
      },
      showDrawer(flag) {
        this.isShowDrawer = true;
        this.activeName = flag;
        this.redisplayTableData(true);
      },
      // 表格回显
      redisplayTableData() {
        // 回显数据user , user-group,user-label
        if (this.activityId && this.activeName === "user") {
          this.$nextTick(() => {
            this.$refs.userListRef.redisplayUser(this.choosedUserList);
          });
        } else if (this.activityId && this.activeName === "user-group") {
          this.$nextTick(() => {
            this.$refs.userGroupRef.redisplayUser(this.choosedUserGroupList);
          });
        } else if (this.activityId && this.activeName === "user-label") {
          this.$nextTick(() => {
            this.$refs.userLabelRef.redisplayUser(this.choosedUserLabelList);
          });
        }
      },
      // 关闭抽屉
      handleCloseDrawer() {
        this.isShowDrawer = false;
      },
      handleClick(val) {
        this.activeName = val.name;
        this.redisplayTableData();
      },
      handleChoosedUserChange(val) {
        this.choosedUserList = val;
      },
      handleUserGroupChange(val) {
        this.choosedUserGroupList = val;
      },
      handleUserLabelChange(val) {
        this.choosedUserLabelList = val;
      },

      // tab切换
      handleChoooseGoodsClick(val) {
        if (val === "choosedList") {
          this.skuList = [];
          this.$refs.chooseSeckillSkuRef.refreshList(this.skuList);
        }
        this.activeChooseGoodsName = val.name;
      },

      // 接收更新的数据
      handleUpdateList(row) {
        let item = this.confirmGoodsSkuList.find(
          (item) => item.product_id === row.product_id
        );
        if (item) {
          item = row;
        }
      },
      // 删除已经选中的全返商品
      handleDeleteItem(row) {
        this.confirmGoodsSkuList = this.confirmGoodsSkuList.filter(
          (item) => item.id !== row.id
        );
        this.skuList = this.skuList.filter((item) => item.id !== row.id);
        this.$refs.displayChooseSeckillSkuRef.refreshList(
          this.confirmGoodsSkuList
        );
        this.$refs.chooseSeckillSkuRef.refreshList(this.skuList);
        if (this.confirmGoodsSkuList.length === 0) {
          this.activeChooseGoodsName = "goChooseGoods";
        }
      },
      // 获取平台商品列表
      getPlatformGoodsList(query) {
        if (query !== "") {
          this.goodsLoading = true;
          getGoodsList({
              keywords: query,
            })
            .then((res) => {
              this.goodsLoading = false;
              const {
                code,
                data,
                msg
              } = res;
              if (code === 200) {
                this.platFormGoodsList = data.list;
              } else {
                this.$message.error(msg);
              }
            })
            .catch((err) => {
              this.goodsLoading = false;
              this.$message.error(err);
            });
        }
      },
      // 参与商品选择改变时
      handleChooseGoodsChange(val) {
        console.log("val==>", val);
        val.product.forEach((item) => {
          this.$set(item, "isConfirm", false);
          this.$set(item, "isUpdate", true);
          this.$set(item, "detail", val);
        });
        this.skuList = val.product;
        this.$nextTick(() => {
          this.$refs.chooseSeckillSkuRef.refreshList(this.skuList);
        });
      },
      handleCurrentChooseGoods(row) {
        // console.log('row==>', row)
        const item = this.confirmGoodsSkuList.find((item) => item.id === row.id);
        if (item) {
          this.$message.warning("该商品已经选择过了！");
          return;
        }
        this.confirmGoodsSkuList.push(row);
      },
      disabledDate(time) {
        var date = new Date("2010-01-01");
        return time.getTime() < date.getTime();
      },
    },
  };
</script>

<style lang="scss" scoped>

  .splitTitle {
    font-size: 16px;
    font-weight: 700;
    color: #606266;

    .split {
      width: 95%;
      border-bottom: 2px solid #c9c9c980;
      padding-bottom: 10px;
      margin: 20px auto;
    }
  }
</style>
<style>
  .el-upload--picture-card {
    width: 90px !important;
    height: 90px !important;
    line-height: 90px;
  }

  .el-upload-list--picture-card .el-upload-list__item-actions {
    width: 90px !important;
    height: 90px !important;
  }

  .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 90px !important;
    height: 90px !important;
  }

  .el-upload-list--picture-card .el-upload-list__item {
    width: 90px !important;
    height: 90px !important;
  }

  .tox .tox-dialog-wrap__backdrop {
    z-index: 9993 !important;
  }

  .tox-tinymce-aux {
    z-index: 9990 !important;
  }

  .tox .tox-dialog {
    z-index: 9995 !important;
  }
</style>
